<template>
  <view class="detail-page">
    <view class="page-header" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="22" color="#fff"></uni-icons>
      </view>
    </view>
    
    <scroll-view class="scroll-content" :scroll-y="true" @scrolltolower="loadMoreComments">
      <!-- 服务主图 -->
      <image class="service-main-image" :src="serviceData.mainImage" mode="aspectFill"></image>

      <!-- 主要信息区 -->
      <view class="service-main-info">
        <view class="service-price">
          <text class="symbol">¥</text><text class="amount">{{ serviceData.price }}</text>
          <text class="unit"> /{{ serviceData.unit }}起</text>
        </view>
        <h1 class="service-title">{{ serviceData.title }}</h1>
        <p class="service-subtitle">{{ serviceData.subtitle }}</p>
      </view>

      <!-- 详情与评论区 -->
      <view class="info-container">
        <view class="details-tabs-wrapper">
          <view class="tab-indicator" :style="{ transform: `translateX(${activeTabIndex * 100}%)` }"></view>
          <view class="tab-button" :class="{active: activeTab === 'details'}" @click="switchTab('details', 0)">服务详情</view>
          <view class="tab-button" :class="{active: activeTab === 'reviews'}" @click="switchTab('reviews', 1)">用户评价 ({{ serviceData.totalComments }})</view>
        </view>

        <!-- 服务详情面板 -->
        <view v-if="activeTab === 'details'" class="details-panel active">
          <h3 class="panel-title">服务范围</h3>
          <p class="panel-content">{{ serviceData.serviceScope }}</p>
          
          <view v-if="serviceData.posters && serviceData.posters.length > 0" class="service-posters">
            <h3 class="panel-title">服务海报</h3>
            <image 
              v-for="(posterUrl, index) in serviceData.posters" 
              :key="index" 
              :src="posterUrl" 
              class="poster-image" 
              mode="widthFix"
            ></image>
          </view>
        </view>
        
        <!-- 评论面板 -->
        <view v-else-if="activeTab === 'reviews'" class="details-panel active">
          <view v-if="serviceData.reviews.length > 0">
              <view class="reviews-summary">
                <!-- 这里的评分和好评率可以从 serviceData 中获取，如果需要的话 -->
                <view>
                  <!-- <text class="score">综合评分 {{ serviceData.rating || '5.0' }}</text> -->
                </view>
                <!-- <text class="score-count">{{ serviceData.goodReviewRate || '100%' }}好评</text> -->
              </view>
              <view class="review-list">
                <view v-for="review in serviceData.reviews" :key="review.id" class="review-card">
                    <view class="review-header">
                        <image :src="review.avatar" class="review-avatar" mode="aspectFill"></image>
                        <view class="review-user-info">
                            <text class="review-user-name">{{ review.username }}</text>
                            <text class="review-time">{{ review.time }}</text>
                        </view>
                        <view class="custom-rating-container-readonly">
                            <image v-for="star in 5" :key="star" class="star-image"
                                :src="star <= review.stars ? '/static/icons/star-filled.svg' : '/static/icons/star-empty.svg'">
                            </image>
                        </view>
                    </view>
                    <p class="review-content">{{ review.content }}</p>
                </view>
              </view>
              <uni-load-more :status="isLoading.comments ? 'loading' : (serviceData.hasMoreComments ? 'more' : 'noMore')"></uni-load-more>
          </view>
          <view v-else class="empty-state">
              <text>暂无评价</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- [修改] 底部固定操作栏 -->
    <view class="sticky-footer" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <!-- 容器本身作为定位基准 -->
      <view class="footer-content">
        <view class="price-info">
          <view class="deposit">
            <text class="label">订金 </text>
            <text class="amount">¥{{ DEPOSIT_AMOUNT.toFixed(2) }}</text>
          </view>
          <view class="final-payment">
            <text>尾款约 ¥{{ finalPayment }}</text>
          </view>
        </view>
        <button class="order-btn" @click="gotoCreateOrder">立即预约</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useSystemInfo } from '@/composables/useSystemInfo';
import { request } from '@/utils/request.js';
import { BASE_URL, DEPOSIT_AMOUNT } from '@/utils/config.js';

const { safeAreaInsets } = useSystemInfo();

// ---- 响应式状态定义 ----
const serviceData = reactive({
  id: null,
  title: '',
  subtitle: '',
  mainImage: '',
  price: '0.00',
  unit: '次', // 接口缺失，暂时硬编码
  serviceScope: '',
  posters: [],
  reviews: [],
  // 评论分页相关
  totalComments: 0,
  currentPage: 1,
  pageSize: 10,
  hasMoreComments: true,
});

const activeTab = ref('details');
const activeTabIndex = ref(0);
const isLoading = ref({ detail: false, comments: false });

// ---- API 请求方法 ----
// [新增] 计算属性，用于动态计算尾款
const finalPayment = computed(() => {
  const totalPrice = parseFloat(serviceData.price);
  if (isNaN(totalPrice)) {
    return '0.00'; // 如果价格无效，返回0
  }
  const result = totalPrice - DEPOSIT_AMOUNT;
  // 确保尾款不会是负数
  return result > 0 ? result.toFixed(2) : '0.00';
});
/**
 * @description 根据服务ID获取服务详情
 * @param {string|number} serviceId
 */
const fetchServiceDetail = async (serviceId) => {
  isLoading.value.detail = true;
  try {
    const data = await request({
      url: `/servicesdetail`, // [修改] 新的URL
      method: 'POST',
      data: { serviceId: serviceId } // [修改] 参数在请求体中
    });
    
    serviceData.id = data.serviceId;
    serviceData.title = data.serviceMainName;
    serviceData.subtitle = data.serviceSubName;
    serviceData.mainImage = `${BASE_URL}${data.serviceHeadImg}`;
    serviceData.price = data.serviceMoney.toFixed(2);
    serviceData.serviceScope = data.serviceScope;
		
		if (data.serviceBodyImg) {
		    serviceData.posters = [`${BASE_URL}${data.serviceBodyImg}`];
		} else {
		    serviceData.posters = []; // 如果没有海报，确保是个空数组
		}
  } catch (error) {
    console.error('获取服务详情失败:', error);
    uni.showToast({ title: '加载服务失败', icon: 'error' });
  } finally {
    isLoading.value.detail = false;
  }
};

/**
 * @description 根据服务ID获取评论列表
 * @param {string|number} serviceId
 */
const fetchServiceComments = async (serviceId) => {
  if (!serviceData.hasMoreComments) return; // 没有更多数据了
  isLoading.value.comments = true;
  try {
    const data = await request({
      url: `/services/showcomments`, // [修改] 新的URL
      method: 'POST',
      data: { 
        serviceId: serviceId,
        pageNum: serviceData.currentPage,
        pageSize: serviceData.pageSize
      }
    });
    
    // [修改] 使用真实的 userName 和 userImg
    const newComments = data.list.map(comment => ({
      id: comment.commentId,
      username: comment.userName, // 使用真实用户名
      avatar: `${BASE_URL}${comment.userImg}`, // 使用真实头像URL
      time: comment.commentDateTime,
      stars: comment.commentStar,
      content: comment.commentContent,
    }));

    // [新增] 处理分页逻辑
    if (serviceData.currentPage === 1) {
        serviceData.reviews = newComments;
    } else {
        serviceData.reviews = [...serviceData.reviews, ...newComments];
    }
    
    serviceData.totalComments = data.total;
    serviceData.hasMoreComments = data.hasNextPage; // 后端返回了分页信息
    
  } catch (error) {
    console.error('获取评论失败:', error);
  } finally {
    isLoading.value.comments = false;
  }
};


// ---- 事件处理方法 ----
const goBack = () => uni.navigateBack();

const switchTab = (tab, index) => {
  activeTab.value = tab;
  activeTabIndex.value = index;
};

const gotoCreateOrder = () => {
  uni.navigateTo({
    url: `/pages/order-create/order-create?serviceId=${serviceData.id}`
  });
};

// [新增] 滚动到底部加载更多评论
const loadMoreComments = () => {
    if (isLoading.value.comments || !serviceData.hasMoreComments) return;
    serviceData.currentPage++;
    fetchServiceComments(serviceData.id);
}

// ---- 生命周期钩子 ----
onLoad((options) => {
  const serviceId = options.id;
  if (!serviceId) {
    uni.showToast({ title: '参数错误', icon: 'error' });
    setTimeout(goBack, 1500);
    return;
  }
  
  fetchServiceDetail(serviceId);
  fetchServiceComments(serviceId);
});
</script>

<style lang="scss" scoped>
.detail-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $uni-bg-color;
}

.page-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
  height: 44px;
  display: flex;
  align-items: center;

  .back-btn {
    width: 72rpx;
    height: 72rpx;
    margin-left: 20rpx;
    background: rgba(0,0,0,0.3);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.scroll-content {
  flex: 1;
  height: 0; /* 修正 scroll-view 在 flex 布局下的高度问题 */
  padding-bottom: 140rpx; // 为底部按钮留出空间
}

.service-main-image {
  width: 100%;
  height: 562rpx;
}

.service-main-info {
  background: $uni-bg-color-white;
  padding: 40rpx;
  margin-top: -40rpx;
  border-top-left-radius: 40rpx;
  border-top-right-radius: 40rpx;
  position: relative;
  
  .service-price {
    font-weight: bold;
    color: $uni-primary;
    margin-bottom: 20rpx;
    .symbol { font-size: 32rpx; }
    .amount { font-size: 52rpx; }
    .unit { font-size: 28rpx; font-weight: normal; }
  }
  .service-title { font-size: 40rpx; font-weight: 500; margin-bottom: 10rpx; color: $uni-text-color;}
  .service-subtitle { font-size: 28rpx; color: $uni-text-color-light; }
}

.info-container {
  margin-top: 20rpx;
  background-color: $uni-bg-color-white;
  padding: 40rpx;
}

.details-tabs-wrapper {
  background-color: $uni-bg-color;
  border-radius: 50rpx;
  padding: 8rpx;
  display: flex;
  position: relative;
  margin-bottom: 50rpx;
  
  .tab-indicator {
    position: absolute;
    top: 8rpx;
    left: 8rpx;
    height: calc(100% - 16rpx);
    width: calc(50% - 8rpx);
    background-color: $uni-primary;
    border-radius: 42rpx;
    box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.3);
    transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  }
  
  .tab-button {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 30rpx;
    font-weight: 500;
    color: $uni-text-color-light;
    position: relative;
    z-index: 1;
    transition: color 0.3s ease;
    &.active { color: $uni-bg-color-white; }
  }
}

.details-panel.active { animation: fadeIn 0.5s; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

.panel-title {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 30rpx;
  padding-left: 20rpx;
  border-left: 6rpx solid $uni-primary;
}
.panel-content {
  font-size: 28rpx;
  line-height: 1.8;
  color: #555;
}

.service-posters {
  margin-top: 50rpx;
  .poster-image {
    width: 100%;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
  }
}

.reviews-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  .score { font-size: 32rpx; font-weight: 500; }
  .score-count { font-size: 28rpx; color: $uni-text-color-light; }
}

.review-card {
  border-bottom: 1px solid $uni-border-color;
  padding: 30rpx 0;
  &:last-child { border-bottom: none; }
  .review-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    .review-avatar { width: 80rpx; height: 80rpx; border-radius: 50%; margin-right: 20rpx; }
    .review-user-info { flex-grow: 1; }
    .review-user-name { font-size: 30rpx; font-weight: 500; }
    .review-time { font-size: 24rpx; color: $uni-text-color-light; }
  }
  .review-content { font-size: 28rpx; line-height: 1.7; }
}

/* [新增] 只读的星星评分样式 */
.custom-rating-container-readonly {
    display: flex;
    align-items: center;
    gap: 4rpx;
    .star-image {
        width: 32rpx;
        height: 32rpx;
    }
}

/* [新增] 空状态样式 */
.empty-state {
    text-align: center;
    padding: 100rpx 0;
    color: $uni-text-color-light;
    font-size: 28rpx;
}


.sticky-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $uni-bg-color-white;
  padding: 20rpx 30rpx; /* 内边距给子元素留出空间 */
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.08);
  
  /* [核心修改] 父容器高度由内容决定，内部使用绝对定位 */
  .footer-content {
    position: relative; /* 设为定位基准 */
    width: 100%;
    height: 90rpx; /* 固定高度，确保元素垂直对齐 */
    display: flex; /* 使用flex只是为了垂直居中，不用于左右布局 */
    align-items: center;
  }

  .price-info {
    /* 左侧价格信息，默认从左边开始 */
    color: $uni-text-color;
  }
  
  .deposit {
    display: flex;
    align-items: baseline;
    margin-bottom: 4rpx;
    .label {
      font-size: 28rpx;
    }
    .amount {
      font-size: 40rpx;
      font-weight: bold;
      color: $uni-primary;
      margin-left: 8rpx;
    }
  }

  .final-payment {
    font-size: 24rpx;
    color: $uni-text-color-light;
  }
  
  .order-btn {
    /* [核心修改] 使用绝对定位，强制放在右侧 */
    position: absolute;
    right: 0; /* 对齐到父容器的右边 */
    top: 50%; /* 垂直居中准备 */
    transform: translateY(-50%); /* 精确垂直居中 */

    padding: 0 80rpx;
    height: 90rpx;
    line-height: 90rpx; /* 确保文字垂直居中 */
    background: linear-gradient(135deg, $uni-primary, $uni-accent);
    color: white;
    border-radius: 45rpx;
    font-size: 32rpx;
    font-weight: 500;
    
    /* 重置uniapp按钮默认样式 */
    margin: 0;
    
    /* 解决按钮文字不显示的问题，明确设置 display 和 text-align */
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>